package com.chagee.channel.server.event.service;

import com.alibaba.fastjson.JSON;
import com.chagee.channel.common.exception.BizErrorCode;
import com.chagee.channel.common.exception.BizException;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author: chang.jiawei
 * @date: 2024/02/20
 */
@Component
@Slf4j
public class MqSender {

    @Resource
    @Qualifier("rocketMQTemplate")
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    @Qualifier("oldRocketMQTemplate")
    private RocketMQTemplate rocketMQTemplateOld;


    public void send(Object eventBody, String topic, String topicTag) {
        try {
            SendResult sendResult = rocketMQTemplate.syncSend(topic + ":" + topicTag, JSON.toJSONString(eventBody).getBytes());
            log.info("lark message mq send result:{}, tag:{}", JSON.toJSONString(sendResult), topicTag);
            if (!sendResult.getSendStatus().equals(SendStatus.SEND_OK)) {
                throw new BizException(BizErrorCode.SEND_MQ_FAIL);
            }
            //send2(eventBody,topic,topicTag);
        } catch (Exception e) {
            log.error("send message fail. topic:{}:{}, body:{}", topic, topicTag, JSON.toJSONString(eventBody), e);
            throw new BizException(BizErrorCode.SEND_MQ_FAIL);
        }
    }
    public void sendOldMQ(Object eventBody, String topic, String topicTag){
        try {
            SendResult sendResult2 = rocketMQTemplateOld.syncSend(topic + ":" + topicTag, JSON.toJSONString(eventBody).getBytes());
            log.info("send2 lark message mq send result:{}, tag:{}", JSON.toJSONString(sendResult2), topicTag);
            if (!sendResult2.getSendStatus().equals(SendStatus.SEND_OK)) {
                throw new BizException(BizErrorCode.SEND_MQ_FAIL);
            }
        } catch (Exception e) {
            log.error("send2 message fail. topic:{}:{}, body:{}", topic, topicTag, JSON.toJSONString(eventBody), e);
            throw new BizException(BizErrorCode.SEND_MQ_FAIL);
        }
    }
}
